import { Button, Flex, Input, Modal, Table, Typography, ConfigProvider, Col } from "antd";
import {request} from "../utils/requset";
import { useEffect, useState } from "react";
import zhCN from 'antd/locale/zh_CN'; // 引入中文语言包
const { Text } = Typography
const pzcolumns = [
    {
        title: '摘要',
        dataIndex: 'zy',
        key: 'zy',
    },
    {
        title: '科目',
        dataIndex: 'kmmc',
        key: 'kmmc',
    },
    {
        title: '借方金额',
        dataIndex: 'jfje',
        key: 'jfje',
        align: 'right',
        render: (dom, rowData, index) => {
            return rowData['jzfx'] === 1 ? <Text strong>{rowData['jfje']}</Text> : null
        }
    },
    {
        title: '贷方金额',
        dataIndex: 'dfje',
        key: 'dfje',
        align: 'right',
        render: (dom, rowData, index) => {
            return rowData['jzfx'] === 2 ? <Text strong>{rowData['dfje']}</Text> : null
        }
    }
];
const xqcolumns = [
    {
        title: '摘要',
        dataIndex: 'zy',
        key: 'zy',
    },
    {
        title: '部门',
        dataIndex: 'bm',
        key: 'bm',
    },
    {
        title: '往来单位',
        dataIndex: 'wldwmc',
        key: 'wldwmc',
    },
    // {
    //     title: '产品',
    //     dataIndex: 'bm',
    //     key: 'bm',
    // },
    {
        title: '项目',
        dataIndex: 'zx02qc',
        key: 'zx02qc',
    },
    {
        title: '职员',
        dataIndex: 'bm',
        key: 'bm',
    },
    {
        title: '记账方向',
        dataIndex: 'jzfx_zh',
        key: 'jzfx_zh',
        width: 80
    },
    {
        title: '金额',
        dataIndex: 'je',
        key: 'je',
        align: 'right',
        render:(text)=>(
            <Text strong>{text}</Text>
        )
    },
    {
        title: '结算日期',
        dataIndex: 'bm',
        key: 'bm',
        width: 120
    },
]

function numberToChinese(num) {
    const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    const cnIntRadice = ['', '拾', '佰', '仟'];
    const cnIntUnits = ['', '万', '亿', '兆'];
    const cnDecUnits = ['角', '分', '厘'];
    const cnInteger = '整';
    let chineseStr = '';
    let numStr = num.toString();
    let parts;

    if (numStr.indexOf('.') === -1) {
        numStr += '.00';
    }

    parts = numStr.split('.');
    const integerNum = parts[0];
    const decimalNum = parts[1].substr(0, 3);

    if (parseInt(integerNum, 10) === 0) {
        chineseStr += cnNums[0];
    } else {
        let zeroCount = 0;
        for (let i = 0; i < integerNum.length; i++) {
            const n = integerNum.substr(i, 1);
            const p = integerNum.length - i - 1;
            const q = Math.floor(p / 4);
            const m = p % 4;

            if (n === '0') {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    chineseStr += cnNums[0];
                }
                chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
                zeroCount = 0;
            }
            if (m === 0 && zeroCount < 4) {
                chineseStr += cnIntUnits[q];
            }
        }
    }
    chineseStr += '元';

    if (decimalNum !== '000') {
        for (let i = 0; i < decimalNum.length; i++) {
            const n = decimalNum.substr(i, 1);
            if (n !== '0') {
                chineseStr += cnNums[Number(n)] + cnDecUnits[i];
            }
        }
    } else {
        chineseStr += cnInteger;
    }

    return chineseStr;
}

export default function Jzpz({ isjzpz, pzdata, handleCancel }) {
    const [pzdataSource, setpzdataSource] = useState([])
    const [xqdataSource, setxqdataSource] = useState([])
    const [selectedRowKeys, setselectedRowKeys] = useState([])
    const [isloading, setisloading] = useState(false)
    const [page, setpage] = useState({
        pageNum: 1,
        pageSize: 10
    })
    const [searchval, setsearchval] = useState('')
    const [pzinfo, setpzinfo] = useState({})
    const getData = async () => {
        setisloading(true)
        setxqisloading(true)
        const response = await request.post('/nw_pz/api/pzk', {
            dwbh: pzdata.dwbh,
            ledger: pzdata.ledger,
            kjnd: pzdata.year,
            kjqj: pzdata.kjqj,
            pzbh: pzdata.pzbh
        });
        response.data.code === 200 && setpzinfo(response.data.data[0])
        const resp = await request.post('/nw_pz/api/pzfl', {
            dwbh: pzdata.dwbh,
            ledger: pzdata.ledger,
            kjnd: pzdata.year,
            pzid: pzdata.pzid,
            kmtx: pzdata.kmtx
        });
        setisloading(false)
        if (response.data.code === 200) {
            resp.data.data.length > 0 && setselectedRowKeys([resp.data.data[0].flid])
            setpzdataSource(resp.data.data.map(item => ({
                ...item,
                key: item.flid
            })))
        }
    }
    const [datatotal, setdatatotal] = useState(0)
    const [xqisloading, setxqisloading] = useState(false)
    const getdetail = async () => {
        setxqisloading(true)
        const resp = await request.post('/nw_pz/api/fzys', {
            dwbh: pzdata.dwbh,
            ledger: pzdata.ledger,
            kjnd: pzdata.year,
            pzid: pzdata.pzid,
            flid: selectedRowKeys[0],
            ...page,
            search: { 'all': searchval }
        });
        setxqisloading(false)
        if (resp.data.code === 200) {
            setdatatotal(resp.data.total)
            setxqdataSource(resp.data.data.map(item => ({
                ...item,
                key: item.fzid
            })))
        }
    }
    useEffect(() => {
        getdetail()
    }, [selectedRowKeys, page, searchval])
    const onSearch = (val) => {
        setsearchval(val)
    }
    const onTableChange = (page, pageSize) => {
        setpage({
            pageSize,
            pageNum: page
        })
    }
    const handleChange = (selectedRowKeys, selectedRows) => {
        setselectedRowKeys(selectedRowKeys)
    }
    useEffect(() => {
        getData()
    }, [])
    return (
        <ConfigProvider locale={zhCN} theme={{
            components:{
                Table:{
                    headerBg:'rgba(22, 93, 255, .05)'
                }
            }
        }}>
            <Modal width={'90%'} maskClosable={false} centered open={isjzpz} title='凭证预览' footer={null} onCancel={handleCancel}>
                <Flex gap={20} vertical style={{ height: '85vh' }}>
                    {/* <Flex gap={12} style={{ marginTop: 15 }}>
                        <Button onClick={handleCancel}>返回</Button>
                        <Button type="primary">打印</Button>
                    </Flex> */}
                    <Flex justify="space-between" align='flex-end'>
                        <Flex gap={10}>
                            <Flex gap={4}>
                                <Typography.Text>凭证字</Typography.Text>
                                <Text keyboard>{pzinfo.pzbh}</Text>
                                <Typography.Text>号</Typography.Text>
                            </Flex>
                            <Flex gap={4}>
                                <Typography.Text>日期</Typography.Text>
                                <Text keyboard>{pzinfo.pzrq}</Text>
                            </Flex>
                        </Flex>
                        <Flex gap={10} align='flex-end'>
                            <Typography.Title style={{ margin: 0 }} level={1}>{pzinfo.pzlx}</Typography.Title>
                            <Typography.Text>{pzinfo.kjnd}年第{pzinfo.kjqj}期</Typography.Text>
                        </Flex>
                        <Flex gap={4}>
                            <Typography.Text>附件</Typography.Text>
                            <Text keyboard>{pzinfo.pjzs}</Text>
                            <Typography.Text>张</Typography.Text>
                        </Flex>
                    </Flex>
                    <Table loading={isloading} scroll={{ y: 'calc((85vh - 400px)/2)' }} size="small" bordered summary={data => {
                        let jftotal = 0;
                        let dftotal = 0;
                        data.forEach(item => {
                            jftotal += +item.jfje
                            dftotal += +item.dfje
                        })
                        return <Table.Summary fixed>
                            <Table.Summary.Row>
                                <Table.Summary.Cell colSpan={3} index={0}>合计：<Text style={{ color: '#165DFF' }} strong>{numberToChinese(Math.abs(jftotal.toFixed(2)))}</Text></Table.Summary.Cell>
                                <Table.Summary.Cell index={2} align="right"><Text style={{ color: '#165DFF' }} strong>{(jftotal.toFixed(2))}</Text></Table.Summary.Cell>
                                <Table.Summary.Cell index={3} align="right"><Text style={{ color: '#165DFF' }} strong>{(dftotal.toFixed(2))}</Text></Table.Summary.Cell>
                            </Table.Summary.Row>
                        </Table.Summary>
                    }} rowSelection={{
                        selectedRowKeys,
                        type: 'radio',
                        onChange: handleChange
                    }} pagination={false} columns={pzcolumns} dataSource={pzdataSource}></Table>
                    <Flex justify="space-between">
                        <Text>财务主管：<Text strong>{pzinfo.kjzg}</Text></Text>
                        <Text>记账：<Text strong>{pzinfo.jzr}</Text></Text>
                        <Text>审核：<Text strong>{pzinfo.shr}</Text></Text>
                        <Text>出纳：<Text strong>{pzinfo.cn}</Text></Text>
                        <Text>制单：<Text strong>{pzinfo.zdr}</Text></Text>
                    </Flex>
                    <Flex gap={12} vertical>
                        <Input.Search style={{ width: '300px' }}
                            allowClear onSearch={onSearch} placeholder="请输入" />
                        <Table loading={xqisloading} scroll={{ y: 'calc((85vh - 400px)/2)' }} size="small" columns={xqcolumns}
                            dataSource={xqdataSource} bordered pagination={{
                                showSizeChanger: true,
                                showQuickJumper: true,
                                total: datatotal,
                                current: page.pageNum,
                                pageSize: page.pageSize,
                                showTotal: ((total) => `共计${total}条`),
                                onChange: onTableChange
                            }}></Table>
                    </Flex>
                </Flex>
            </Modal>
        </ConfigProvider>
    )
}
